package me.wang.qrcodepay;

import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.map.MapCanvas;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;

import static me.wang.qrcodepay.QRcodePay.plugin;


public class QRcode {
    public static ItemStack createQRCodeMap(String text,String name,String url,Boolean isImage) throws IOException {
        ItemStack mapItem = new ItemStack(Material.MAP);
        World world = plugin.getServer().getWorlds().get(0);
        MapView mapView = plugin.getServer().createMap(world);
        mapView.setScale(MapView.Scale.CLOSEST);
        for (MapRenderer renderer : mapView.getRenderers()) {
            mapView.removeRenderer(renderer);
        }
        mapView.addRenderer(new QRCodeMapRenderer(text,name,url,isImage));
        short mapId = mapView.getId();
        mapItem.setDurability(mapId);
        return mapItem;
    }

    public static class QRCodeMapRenderer extends MapRenderer {
        private final String text;
        private final String name;
        private final Image image;
        private final Boolean isImage;
        private boolean rendered = false;

        public QRCodeMapRenderer(String text,String name,String url,Boolean isImage) throws IOException {
            this.text = text;
            this.name = name;
            if (!isImage){
                this.image = ImageIO.read(new URL(url));
            }else {
                this.image = null;
            }
            this.isImage = isImage;
        }

        @Override
        public void render(MapView map, MapCanvas canvas, Player player) {
            if (rendered) return;

            try {
                Image image1;
                if (isImage){
                    File qrCodeFile = new File(plugin.getDataFolder(), name+".png");
                    QrCodeUtil.generate(text, QrConfig.create().setWidth(128).setHeight(128), qrCodeFile);
                    image1 = ImageIO.read(qrCodeFile);
                    Files.delete(qrCodeFile.toPath());
                }else {
                    image1 = image;
                }
                canvas.drawImage(0 ,0 , image1);
                rendered = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
